package com.weimengchao.common.algorithm;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.shardingsphere.sharding.api.sharding.hint.HintShardingAlgorithm;
import org.apache.shardingsphere.sharding.api.sharding.hint.HintShardingValue;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * 强制路由分片算法
 */
@Slf4j
public final class ShardingValueHintShardingAlgorithm implements HintShardingAlgorithm<Integer> {

    @Override
    public Collection<String> doSharding(Collection<String> availableTargetNames, HintShardingValue<Integer> shardingValue) {
        if (log.isDebugEnabled()) {
            log.debug("availableTargetNames: {}, shardingValue: {}", JSON.toJSONString(availableTargetNames), JSON.toJSONString(shardingValue));
        }
        List<String> tableNames = new ArrayList<>();
        String logicTableName = shardingValue.getLogicTableName();
        Collection<Integer> values = shardingValue.getValues();
        for (Integer value : values) {
            String tableName = new StringBuffer().append(logicTableName).append(value).toString();//拼接目标表名
            tableNames.add(tableName);
        }
        //取交集
        tableNames.retainAll(availableTargetNames);
        return tableNames;
    }

}
